package com.yql.biz.core.filter;

import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;
import com.yql.common.utils.StringUtils;
import com.yql.common.utils.logs.CommonLogUtil;
import com.yql.commonextend.utils.TripleDesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.PatternSyntaxException;

/**
 * @description:报文解密
 * @Date: 2021-06-28
 * @Time: 15:26
 */
public class ParameterRequestWrapper extends HttpServletRequestWrapper {

    private static Logger logger = LoggerFactory.getLogger(ParameterRequestWrapper.class);
    private byte[] body = null;
    private Map<String, String[]> params = new LinkedHashMap<>();//与父类中数据结构一致
    public static final String PARAMS = "params";//params 前端统一参数key
    public static final String VERSION = "api_version";//version版本号
    private static final String ENCODING = "UTF-8";

    public ParameterRequestWrapper(HttpServletRequest request) throws UnsupportedEncodingException {
        //将request交给父类，以便于调用对应方法的时候，将其输出，其实父亲类的实现方式和第一种new的方式类似
        super(request);
        Map<String, String[]> requestMap = request.getParameterMap();
        this.params.putAll(requestMap);
        this.modifyParameterValues();
        //读取流中的参数
            String sessionStream = getBodyString(request);
            if (StringUtils.isNotEmpty(sessionStream)) {
                sessionStream = this.modifyParams(sessionStream);
                this.body = sessionStream.getBytes(Charset.forName(ENCODING));
            }
       request.setAttribute("error", new Exception());
    }

    private String modifyParams(String json) throws UnsupportedEncodingException {

        JSONObject jsonObject = JSONUtil.parseObj(json);
        String paramsStr = jsonObject.getStr(PARAMS);
        logger.info("请求加密报文：" + JSONUtil.toJsonStr(paramsStr));
        CommonLogUtil.info(new Throwable(), "{}",
                new StringBuffer().append("【请求加密报文】:").append(JSONUtil.toJsonStr(paramsStr)));

        json = StringFilterUntil(paramsStr);

        CommonLogUtil.info(new Throwable(), "{}",
                new StringBuffer().append("【请求报文解密】:").append(JSONUtil.toJsonStr(json)));

        JSONObject object = JSONUtil.parseObj(json);
        Iterator iter = object.entrySet().iterator();
        Map<String, String[]> resParams = new LinkedHashMap<>();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            resParams.put(entry.getKey().toString(), new String[]{entry.getValue().toString()});
        }
        resParams.put(VERSION, new String[]{jsonObject.getStr(VERSION)});
        params.putAll(resParams);
        return json;
    }

    /**
     * 将parameter的值去除空格后重写回去
     */
    public void modifyParameterValues() throws UnsupportedEncodingException {
        Map<String, String[]> resParams = new LinkedHashMap<>();
        Set<String> set = params.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String[] values = params.get(key);
            if (key.equals(PARAMS)) {
                if (StringUtils.isNotEmpty(values[0])) {
                    values[0] = StringFilterUntil(values[0].trim());
                    resParams = paramsConversion(values);
                }
            }
            params.put(key, values);
        }
        params.putAll(resParams);
    }


    /**
     * 获取请求Body
     *
     * @param request
     * @return
     */
    public String getBodyString(final ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = cloneInputStream(request.getInputStream());
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            logger.error("==ParameterRequestWrapper==IOException异常1：",e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("==ParameterRequestWrapper==IOException异常2：",e);
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("==ParameterRequestWrapper==IOException异常3：",e);
                }
            }
        }
        return sb.toString();
    }

    /**
     * Description: 复制输入流</br>
     *
     * @param inputStream
     * @return</br>
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            logger.error("==ParameterRequestWrapper==IOException异常4：",e);
        }
        InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return byteArrayInputStream;
    }

    /**
     * 参数解密
     *
     * @param str 参数值
     * @return
     * @throws PatternSyntaxException
     */
    public static String StringFilterUntil(String str) throws PatternSyntaxException, UnsupportedEncodingException {
        str = str.replace("*", "%2A").replace("+", "%2B").replace("%7E", "~");
        str = java.net.URLDecoder.decode(str, ENCODING);
        TripleDesUtils tripleDesUtils = new TripleDesUtils();
        String value = tripleDesUtils.TripleDesDecrypt(str);
        return value;
    }

    /**
     * 将String的json参数转换为多个参数
     *
     * @param values String的json串
     * @return
     */
    public static Map paramsConversion(String[] values) {
        Map<String, String[]> resultParams = new LinkedHashMap<>();
        JSONObject jsonObject = JSONUtil.parseObj(values[0]);
        Iterator iter = jsonObject.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String pKey = entry.getKey().toString();

            if (null != entry.getValue()) {
                String pVal = entry.getValue().toString();
                String[] pValues = new String[]{pVal};
                resultParams.put(pKey, pValues);
            } else {
                resultParams.put(pKey, new String[]{});
            }
        }
        return resultParams;
    }

    /**
     * 重写getParameter 参数从当前类中的map获取
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    /**
     * 重写getParameterValues
     */
    @Override
    public String[] getParameterValues(String name) {//同上
        return params.get(name);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }

        };
    }
}
